package com.harvest.scientific.ladder.ext

import android.graphics.*
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.ImageView

fun View.setHeight(value: Int) {
    val lp = layoutParams
    lp?.let {
        lp.height = value
        layoutParams = lp
    }
}

fun View.setWidth(value: Int) {
    val lp = layoutParams
    lp?.let {
        lp.width = value
        layoutParams = lp
    }
}

fun View.resize(width: Int, height: Int) {
    val lp = layoutParams
    lp?.let {
        lp.width = width
        lp.height = height
        layoutParams = lp
    }
}

fun View.setMargin(
    leftMargin: Int = -1,
    topMargin: Int = -1,
    rightMargin: Int = -1,
    bottomMargin: Int = -1
) {
    asLayoutParams<MarginLayoutParams>().let {
        if (leftMargin != -1) {
            it.leftMargin = leftMargin
        }
        if (topMargin != -1) {
            it.topMargin = topMargin
        }
        if (rightMargin != -1) {
            it.rightMargin = rightMargin
        }
        if (bottomMargin != -1) {
            it.bottomMargin = bottomMargin
        }
        layoutParams = it
    }

}

fun View.setMarginSize(size: Int) {
    setMargin(size, size, size, size)
}

fun View.enable() {
    val colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(1f) })
    val paint = Paint()
    paint.colorFilter = colorFilter
    this.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
}

fun View.disable() {
    kotlin.runCatching {
        val colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) })
        if (this is ImageView) {
            setColorFilter(colorFilter)
        } else {
            val paint = Paint()
            paint.colorFilter = colorFilter
            this.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
        }
        this.isEnabled = false
    }.onFailure {}
}

@Suppress("UNCHECKED_CAST")
inline fun <T : ViewGroup.LayoutParams> View.asLayoutParams() = layoutParams as T
